package com.example.rg1musicplayerapp;

import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
//把功能封装到服务里
public class PlayMusicService extends Service {

    private MediaPlayer mediaPlayer;
    private PlayMusicBinder playMusicBinder;
    public PlayMusicService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return new PlayMusicBinder();
    }
    //解绑
    @Override
    public boolean onUnbind(Intent intent) {
        if(mediaPlayer!=null)
        {
            mediaPlayer.stop();
            //释放
            mediaPlayer.release();
            mediaPlayer=null;
        }
        return super.onUnbind(intent);
    }
    //绑定者
    class PlayMusicBinder extends Binder
    {
        //开始播放音乐
        public void startPlay()
        {
            if(mediaPlayer==null)
            {
                mediaPlayer=MediaPlayer.create(PlayMusicService.this,R.raw.canon);
                //播放的资源类型
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mediaPlayer.start();
            }
            else
            {
                mediaPlayer.start();
            }
        }

        //暂停或继续播放音乐
        public void PauseorContinue()
        {
            if(mediaPlayer!=null && mediaPlayer.isPlaying())
            {
                mediaPlayer.pause();
            }
            else if(mediaPlayer!=null && !(mediaPlayer.isPlaying()))
            {
                mediaPlayer.start();
            }
        }

        //获取播放的进度:progressBar
        public int getProgress()
        {
            if(mediaPlayer!=null)
            {
                //获取当前播放位置/总的播放长度*100   保证进度在0-100之间
                return (100*mediaPlayer.getCurrentPosition()/mediaPlayer.getDuration());
            }
            else
            {
                return 0;
            }
        }

        //设置播放的进度:seekBar
        public void seekProgress(int progress)
        {
            if(mediaPlayer!=null)
            {
                mediaPlayer.seekTo(progress*mediaPlayer.getDuration()/100);
            }
        }
    }

}
